<?php
class Login extends MX_Controller {
	function Login()
	{
		parent::__construct();
		$this->lang->load('error', $this->public_model->getLanguage());
	}
	
	function index()
	{
		$is_ajax_call = $this->input->post('is_ajax_call');
		$this->load->model("public_model");	
		$webstoreObj=$this->public_model->getTemplateForUrl();
		$template=$webstoreObj['templatecode'];
		$templateUrl=base_url().'/application/views/templates/'.$template ;
		
		$var['templateUrl'] = $templateUrl;
		
		if($this->is_logged_in()){
			redirect(base_url());
			return;
		}
		
		if(isAccessFromMobile()) {
   			$content=$this->load->view('mobile/login_form',$var,true);
   		} else {
   			$var['miniform'] = false;
   			$content=$this->load->view('login_form',$var,true);
   		}
   		
   		if($is_ajax_call == "yes"){
   			echo $content;	
   		}else{
   			Template::display($content);	
   		}				
	}
	
	function show_forgot_password()
	{
		$this->load->model("public_model");	
		$webstoreObj=$this->public_model->getTemplateForUrl();
		$template=$webstoreObj['templatecode'];
		$templateUrl=base_url().'/application/views/templates/'.$template ;		
		$var['templateUrl'] = $templateUrl;
		if(isAccessFromMobile()) {
   			$content=$this->load->view('mobile/forgot_password',$var,true);
   		} else {
   			$content=$this->load->view('forgot_password',$var,true);
   		}
		Template::display($content);		
	}
    
	function proccess_forgot_password()
	{
		$this->load->model('membership_model');
		$email = $this->input->post('email') ;
		$email = $this->input->post('emailaddress') ;
		if(!empty($email) && !empty($email) ) {
			
			$user = $this-> membership_model->get_member_info($email,$email,null,null) ;
			if($user) {
				if ($user->active != 1) {
					echo "Fail". "|" ."Your account must be active to use this function.";
				} else {
					$tempPassword = $this-> membership_model->get_random_password();
					$encryptPass = md5($tempPassword);			
					$user->passwd = $encryptPass;
					$user->password_expired = 1;
					$user->active = 1;
					$this-> membership_model->update_member_change_password($user);
				
					$user->passwd = $tempPassword;
					$this-> membership_model->sendResetPasswordEmail($user);					
				
					echo "Pass". "|" ."Your password has been reset to the temporary password. Please check your email. ";	
				}
				
			} else {
				echo "Fail". "|" ."User Name and Email Address does not match. Please check again.";
			}
			
		}
		
	}
	
	function activate($userid,$expiredcode) {
		
		$this->load->model('membership_model');
		$user = $this-> membership_model->verify_member_info($userid,$expiredcode) ;
	
		if($user) {
			$exp_date = $user->email_link_expires; 
			$todays_date = date("Y-m-d"); 
			$today = strtotime($todays_date);
			$expiration_date = strtotime($exp_date);	
			if ( $expiration_date >= $today ) { 
				 $var['result'] = "pass";
				 $this-> membership_model->update_member_login($user);
			} else { 
				$var['result'] = "fail";				 
			} 
		} else {
			$var['result'] = "fail";
		}		 
		
		if(isAccessFromMobile()) {
   			$content=$this->load->view('mobile/verify_successful', $var,true);	
   		} else {
   			$content=$this->load->view('verify_successful', $var,true);	
   		}			
		Template::display($content);
	}
		
	function validate_credentials()
	{		
		$this->load->model('membership_model');
		$this->load->helper('date');
		$url=base_url();
		$user = $this->membership_model->validate();
		$referUrl= $this->session->userdata('refered_from');		
		$loca=$this->input->post('loca');	
		if($user) // if the user's credentials validated...
		{
			$type = $user->usertype;
			$userid = $user->id;
			$sellerid=$user->seller_id;
			
			if ($user->active == 0) 
			{
				echo "Fail". "|" . "Account is inactive. Please contact web administrator for more information.";
			} 
			else 
			{
				$data = array(
					'id' => $userid,
					'email' => $this->input->post('email'),
					'fullname' => $user->first_name. ' '. $user->last_name,
					'is_logged_in' => true,
					'usertype' => $type,
					'sellerid' => $sellerid			
				);
				
				$this->session->set_userdata($data);
					
				if( $user->password_expired==1) {					
					if($this->is_admin_logged_in() ){
						$url = base_url() .'maintainuser/showChangePassword' ;
						echo "Pass". "|" . $url;
					}else{
						$url = base_url() .'login/showChangePassword';
						echo "Pass". "|" . $url;
						return;
					}
                    if ($this->is_admin_logged_in())
                        $this->session->set_userdata('refered_from','admin');
                    if ($this->is_user_logged_in())
                        $this->session->set_userdata('refered_from','buyerprofile');
                    else if ($this->is_seller_logged_in())
                        $this->session->set_userdata('refered_from','sellerprofile');
                      				
				}
				else if( $this->is_admin_logged_in()) {
					$url = base_url();
					echo "Pass". "|" . $url;
				}
				else if( $this->is_seller_logged_in()) {
					echo "Pass". "|" . $url;
				}
				//start save to wishlist
				else if( $this->is_user_logged_in()) {
					echo "Pass". "|" . base_url();
					
//					//add to wish list
//					if(isset($urlProductList)&&$urlProductList!=""){
//						$urlProductList = base_url()."productlist/viewProductList";
//						echo "Pass". "|" . $urlProductList;
////					//default to order page
//					}else if(empty($referUrl)){
//						echo "Pass". "|" . base_url()."order/buyer";
//					//go to cart page
//					}else{
//						echo "Pass". "|" . $url;
//					}
				}
			}
		}
		else // incorrect email or password
		{
			echo "Fail". "|" ."Invalid Email or Password.";
		}
	}	
	
	function playerSignup(){
		$is_ajax_call = $this->input->post('is_ajax_call');		
		$this->load->model("membership_model");
		$var = $this->membership_model->populdateBuyerSignupInfo();
		$this->membership_model->getCreditCardData($var);
		
		if(isAccessFromMobile()) {
			//$content=$this->load->view('login/mobile/buyer_signup_form', $var,true);	
		}else{
			$content=$this->load->view('login/player_signup_form', $var,true);		
		}
		
		if($is_ajax_call == "yes"){
   			echo $content;	
   		}else{
   			Template::display($content);	
   		}
	}
	
	function createPlayer(){
		$this->load->library('form_validation');
		
		$response = new stdClass(); 
        $response->success = false;
		$response->content = '';
		$response->message = null;
		$response->commonResponse = new stdClass();
		
		//validation
		$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[6]|valid_email|callback_isExistEmail');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]');
		$this->form_validation->set_rules('confirmpassword', 'Confirm Password', 'trim|required|matches[password]');
		$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|max_length[100]');
		$this->form_validation->set_rules('lastname', 'Last Name', 'trim|required|max_length[100]');
        $this->form_validation->set_rules('lastname', 'Last Name', 'trim|required|max_length[100]');
        $this->form_validation->set_rules('i_agree', 'Accept terms must be checked', 'required');
        
        //end validation	
		if($this->form_validation->run($this) == FALSE)
		{
			if(isAccessFromMobile()) {
				$content = $this->load->view('mobile/player_signup_form', null,true);	
			}else{
				$content = $this->load->view('player_signup_form',null,true);
			}
			$response->content = $content;	
		}else{
			$response = $this->membership_model->createPlayer();
            
			if($response->success){
				$response->content = $this->load->view('signup_successful', '',true);	
			}else{
				if(isAccessFromMobile()) {
					$content = $this->load->view('mobile/player_signup_form', null,true);	
				}else{
					$content = $this->load->view('player_signup_form', null,true);
				}
				$response->content = $content;
			}
		}
        echo json_encode($response);
	}	
	
    function is_logged_in()
	{
		$is_logged_in = $this->session->userdata('is_logged_in');
		if(!isset($is_logged_in) || $is_logged_in != true)
		{
			return false;
		} else {
			return true;
		}
	}
	
	function is_admin_logged_in() {
		$is_logged_in = $this->session->userdata('is_logged_in');		
		if(isset($is_logged_in) && $is_logged_in == 1) {			
			$usertype= $this->session->userdata('usertype');			
			if( isset($usertype) && $usertype == USER_TYPE_ADMIN) {
				return true;
			}
		}
		return false;	
	}
	
	function is_user_logged_in() {
		$is_logged_in = $this->session->userdata('is_logged_in');		
		if(isset($is_logged_in) && $is_logged_in == 1) {			
			$usertype= $this->session->userdata('usertype');			
			if( isset($usertype) && $usertype == USER_TYPE_USER) {
				return true;
			}	
		}
		return false;	
	}
	
	function is_seller_logged_in() {
		$is_logged_in = $this->session->userdata('is_logged_in');		
		if(isset($is_logged_in) && $is_logged_in == 1) {			
			$usertype= $this->session->userdata('usertype');			
			if( isset($usertype) && $usertype == USER_TYPE_SELLER) {
				return true;
			}	
		}
		return false;	
	}
	
	function logout()
	{
		$this->session->unset_userdata('id');
		$this->session->unset_userdata('email');
		$this->session->unset_userdata('is_logged_in');
		$this->session->unset_userdata('fullname');
		$this->session->unset_userdata('usertype');
		$this->session->unset_userdata('sellerid');
		$this->session->unset_userdata('count');
		$this->session->unset_userdata('refered_from');
		//$this->session->sess_destroy();
		$this->index();
	}
	
	function showForgotPassword()
	{

   		$content=$this->load->view('login/forgot_password',false,true);
		echo ($content);		
	}
	
	function validatephone($phone2=''){
		$this->load->library('form_validation');
		if(strlen($phone2)<=0){
			return true;
		}
	 	$phone2=str_replace('-','',$phone2);
	 	if(strlen($phone2)!=7){
	 		$this->form_validation->set_message( 'validatephone', 'The %s field must be exactly 7 numberics in length' );
	 		return false;
	 	}else{
	 		return true;	
	 	}
	}
	
	function isExistEmail($email = ''){
		$this->load->library('form_validation');
	 	if($this->membership_model->getUsers(array('email' => $email)) != false){
	 		$this->form_validation->set_message( 'isExistEmail', 'This %s is already exist. Please choose another one.');
	 		$rs = false;
	 	}else{
	 		$rs = true;
	 	}
	 	
	 	return $rs;
	}
}